package com.rykj.qxj.apiService.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import apiRedis.DynamicRedisPoolUtil;
import com.alibaba.fastjson.JSONObject;
import com.rykj.qxj.server.common.utils.CollectionUtils;
import com.rykj.qxj.server.model.entity.ApiManage;
import com.rykj.qxj.server.model.entity.DatabaseSource;
import com.rykj.qxj.server.services.IDatabaseSourceService;
import com.rykj.qxj.server.util.object.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.rykj.qxj.apiService.exception.ApiIsDeleteException;
import com.rykj.qxj.apiService.exception.ApiIsDisableException;
import com.rykj.qxj.apiService.exception.ApiVersionIsDeleteException;
import com.rykj.qxj.apiService.exception.ApiVersionIsDisableException;
import com.rykj.qxj.apiService.exception.ApiVersionIsNotVerifyPassException;
import com.rykj.qxj.apiService.exception.AppKeyIsNotExistException;
import com.rykj.qxj.apiService.exception.AppKeyIsNotNullException;
import com.rykj.qxj.apiService.exception.ApplyIsNotCurrentApplyException;
import com.rykj.qxj.apiService.exception.ApplyIsNotOnException;
import com.rykj.qxj.apiService.exception.DatabaseSourceIsNullException;
import com.rykj.qxj.apiService.exception.DoAuthenticationFailException;
import com.rykj.qxj.apiService.exception.PageNoOrPageSizeNotRightException;
import com.rykj.qxj.apiService.exception.RequestParamIsNotMatchException;
import com.rykj.qxj.apiService.exception.RequestURIErrorException;
import com.rykj.qxj.apiService.service.IDataApiService;
import com.rykj.qxj.result.BaseResponse;
import com.rykj.qxj.result.ErrType;

import lombok.extern.log4j.Log4j;

@Log4j
@RestController
@RequestMapping("**/data-api")
public class DataApiController {
	@Autowired
	private IDataApiService dataApiService;
	@Autowired
	private IDatabaseSourceService databaseSourceService;
	@PostMapping("/**")
	public BaseResponse doPostService(HttpServletRequest request,HttpServletResponse response) {
		try {
			BaseResponse doPostService = dataApiService.doPostServiceByAppKey(request, response);
			doGetResult(doPostService,response);
		} catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_NULL.getCode(),e.getMessage(),null),response);
		} 
		//catch (DoAuthenticationFailException e) {
			//e.printStackTrace();
			//doGetResult(new BaseResponse(ErrType.DO_AUTHENTICATION_FAIL.getCode(),e.getMessage(),null),response);
		//} 
	     catch (RequestParamIsNotMatchException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_PARAM_IS_NOT_MATCH.getCode(),e.getMessage(),null),response);
		}  catch (DatabaseSourceIsNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DATABASESOURCE_IS_NULL.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (AppKeyIsNotExistException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_EXIST.getCode(),e.getMessage(),null),response);
		} catch (IOException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.READ_REQUESTBODY_CONTENT_FAIL.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotCurrentApplyException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_CURRENT_APPLY.getCode(),e.getMessage(),null),response);
		}
		return null;
	}

	/**
	 * redis:10.151.225.26 密码: 8b21416691e6214172fe6ee3070266244d2f0583dbd65f32e506760e6366484d
	 * @param request
	 * @param response
	 * @return
	 */
	@GetMapping("/**")
	public BaseResponse doGetService(HttpServletRequest request,HttpServletResponse response) {
		try {
			BaseResponse baseResponse = new BaseResponse();
			ApiManage apiManage = dataApiService.getApiManage(request.getRequestURI().replace("/weather-api", ""),request.getMethod());
			if("redis".equals(apiManage.getDatabaseType())){
				String appKey=request.getHeader("appKey");
				if(StringUtils.isEmpty(appKey)){
					appKey=request.getParameter("appKey");
				}
				dataApiService.checkAppkey(appKey);
				Map<String, String[]> parameterMap = request.getParameterMap();
				JSONObject jsonParam =new JSONObject();
				Set<String> keys= parameterMap.keySet();
				for (String key : keys) {
					jsonParam.put(key, parameterMap.get(key)[0]);
				}
				DatabaseSource databaseSource = databaseSourceService.getDatabaseSourceDetails(apiManage.getDatabaseSourceId());
				if(StringUtils.isNotEmpty(jsonParam.getString("key"))&&!DynamicRedisPoolUtil.keyIsExis(databaseSource.getDatabaseIP(),databaseSource.getPort(),databaseSource.getPassword(),jsonParam.getString("key"))){
					baseResponse = new BaseResponse(ErrType.KEY_NO_EXIS.getCode(), ErrType.KEY_NO_EXIS.getMessage());
				}else {
					Object redList = dataApiService.doGetServiceByAppKeyRedis( apiManage, databaseSource,jsonParam);
					if (redList == null || CollectionUtils.objCheckIsNull(redList)) {
						baseResponse = new BaseResponse(ErrType.DATA_IS_NULL.getCode(), ErrType.DATA_IS_NULL.getMessage(), redList);
					} else {
						baseResponse = new BaseResponse(ErrType.SUCCESS.getCode(), ErrType.SUCCESS.getMessage(), redList);
					}
				}
			}else {
				PageInfo page = dataApiService.doGetServiceByAppKey(request, response, apiManage);
				List<Map<String, String>> list = new ArrayList<Map<String, String>>();
				if (page != null && page.getList() != null) {
					for (Object obj : page.getList()) {
						Map<String, String> map = (Map) obj;
						for (String key : map.keySet()) {
							map.put(key, String.valueOf(map.get(key)));
						}
						list.add(map);
					}
					page.setList(list);
				}
			 baseResponse = new BaseResponse(ErrType.SUCCESS.getCode(), ErrType.SUCCESS.getMessage(), page);
			}
			doGetResult(baseResponse,response);
		} catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_NULL.getCode(),e.getMessage(),null),response);
		} catch (DoAuthenticationFailException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DO_AUTHENTICATION_FAIL.getCode(),e.getMessage(),null),response);
		} catch (RequestParamIsNotMatchException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_PARAM_IS_NOT_MATCH.getCode(),e.getMessage(),null),response);
		} catch (DatabaseSourceIsNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DATABASESOURCE_IS_NULL.getCode(),e.getMessage(),null),response);
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (AppKeyIsNotExistException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_EXIST.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotCurrentApplyException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_CURRENT_APPLY.getCode(),e.getMessage(),null),response);
		} catch (PageNoOrPageSizeNotRightException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.PAGENO_PAGESIZE_IS_NOT_REIGHT.getCode(),e.getMessage(),null),response);
		}
		catch (Exception e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.SQL_TEMPLATE_FAIL.getCode(),e.getMessage(),null),response);
		}
		return null;
	}
	/**
	 * 第三方接口调用
	 */
	@GetMapping("/outSide/**")
	public Object doGetOutSideService(HttpServletRequest request,HttpServletResponse response) {
		try {
			 Object result = dataApiService.doGetOutSideService(request, response);
			//BaseResponse baseResponse = new BaseResponse(ErrType.SUCCESS.getCode(), ErrType.SUCCESS.getMessage(), doGetOutSideService);
			//doGetResult(baseResponse,response);
			 return result ;
		} catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (AppKeyIsNotExistException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_EXIST.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotCurrentApplyException e) {
			e.printStackTrace();
			return e.getMessage();
			//doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_CURRENT_APPLY.getCode(),e.getMessage(),null),response);
		} 
		//return "";
	}
	@GetMapping("/file/**")
	public void doGetFileService(HttpServletRequest request,HttpServletResponse response) {
		try {
		    dataApiService.doGetFileServiceByAppKey(request, response);
		} catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
		    doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_NULL.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		//} 
		//catch (FileApiExpiresOSSAccessKeyIdSignatureIsNullException e) {
		//	e.printStackTrace();
		//	doGetResult(new BaseResponse(ErrType.FILE_API_EXPIRES_OSSSACESSKEYID_SIGNATURE_IS_NULL.getCode(),e.getMessage(),null),response);
		//} catch (DoAuthenticationFailException e) {
		//	e.printStackTrace();
		//	doGetResult(new BaseResponse(ErrType.DO_AUTHENTICATION_FAIL.getCode(),e.getMessage(),null),response);
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (IOException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DO_GET_OSSFILE_INPUTSTREAM_FAIL.getCode(),e.getMessage(),null),response);
		} catch (AppKeyIsNotExistException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_EXIST.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotCurrentApplyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	@PutMapping("/**")
	public BaseResponse doPutService(HttpServletRequest request,HttpServletResponse response) {
		try {
			BaseResponse doPutService = dataApiService.doPutService(request, response);
			doGetResult(doPutService,response);
		} catch (DatabaseSourceIsNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DATABASESOURCE_IS_NULL.getCode(),e.getMessage(),null),response);
		}  catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_NULL.getCode(),e.getMessage(),null),response);
		} catch (DoAuthenticationFailException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DO_AUTHENTICATION_FAIL.getCode(),e.getMessage(),null),response);
		} catch (RequestParamIsNotMatchException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_PARAM_IS_NOT_MATCH.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		}
		return null;
	}
	@DeleteMapping("/**")
	public BaseResponse doDeleteService(HttpServletRequest request,HttpServletResponse response) {
		try {
			BaseResponse doDeleteService = dataApiService.doDeleteService(request, response);
			doGetResult(doDeleteService,response);
		} catch (AppKeyIsNotNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPKEY_IS_NOT_NULL.getCode(),e.getMessage(),null),response);
		} catch (DatabaseSourceIsNullException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DATABASESOURCE_IS_NULL.getCode(),e.getMessage(),null),response);
		} catch (RequestParamIsNotMatchException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_PARAM_IS_NOT_MATCH.getCode(),e.getMessage(),null),response);
		} catch (DoAuthenticationFailException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.DO_AUTHENTICATION_FAIL.getCode(),e.getMessage(),null),response);
		} catch (ApplyIsNotOnException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APPLY_IS_NOT_ON.getCode(),e.getMessage(),null),response);
		} catch (RequestURIErrorException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.REQUEST_URL_ERROR.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.API_IS_DELETE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDisableException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DISABLE.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsNotVerifyPassException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_NOT_VERIFY_PASS.getCode(),e.getMessage(),null),response);
		} catch (ApiVersionIsDeleteException e) {
			e.printStackTrace();
			doGetResult(new BaseResponse(ErrType.APIVERSION_IS_DELETE.getCode(),e.getMessage(),null),response);
		}
		return null;
		
	}
	/**
	 * 
	 * @Description: 将调用本地接口的返回的数据以统一的格式返回给调用方
	 * @param:resultResponse 封装的结果集队对象     
	 * @date:   2019年4月9日 上午9:53:46  
	 * @author: wangshunyi    
	 * @throws
	 */
	private void doGetResult(BaseResponse resultResponse,ServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		ObjectMapper mapper=new ObjectMapper();
		String resultJson="";
		try {
			resultJson = mapper.writeValueAsString(resultResponse);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		PrintWriter printWriter;
		try {
			printWriter = response.getWriter();
			printWriter.write(resultJson);
			printWriter.flush();
			printWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	public  String getRequestBodyStr(ServletRequest request) throws IOException {
		BufferedReader reader = request.getReader();
		String str;
		String wholeStr="";
		while((str=reader.readLine())!=null) {
			wholeStr+=str;
		}
		return wholeStr;
	}
  }


